
package com.eltonkent.ui;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.eltonkent.R;
import com.eltonkent.db.SafeEntryTable;
import com.eltonkent.ui.containers.TemplateFieldContainer;
import com.eltonkent.util.DateUtil;
import com.eltonkent.util.ImageUtil;

public class EditTemplateActivity extends ParentActivity
{

	private LinearLayout contentView;
	private String templateName;
	private String templateUID;
	private String iconId;
	private String folderName;
	private boolean isNewTemplate;
	private static final int DLG_DATE_PICKER = 18;
	// private static final int DLG_ADD_FIELD = 22;
	private EditText currentEditText;
	private ArrayList<TemplateFieldContainer> entryFieldList;

	private View.OnFocusChangeListener dateFieldFocusListener = new View.OnFocusChangeListener()
	{

		@Override
		public void onFocusChange(View view, boolean flag)
		{
			if(flag)
			{
				Log.d("UI", "Focus recieved for " + view);
				currentEditText = (EditText) view;
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(currentEditText.getWindowToken(), 0);
				if(currentEditText.getText().toString().equals(""))
					showDialog(DLG_DATE_PICKER);
				// text.setText(String.valueOf(System.currentTimeMillis()));
			}
		}

	};

	private View.OnClickListener dateFieldClickListener = new View.OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			currentEditText = (EditText) view;
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(currentEditText.getWindowToken(), 0);
			showDialog(DLG_DATE_PICKER);
		}
	};

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
	{

		@Override
		public void onDateSet(DatePicker datepicker, int year, int month, int day)
		{
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.YEAR, year);
			calendar.set(Calendar.MONTH, month);
			calendar.set(Calendar.DAY_OF_MONTH, day);
			currentEditText.setText(DateUtil.getFormattedDate(calendar.getTime()));
		}
	};

	private String template;

	private void addTemplateField(TemplateFieldContainer fieldDescriptor, LayoutInflater inflater)
	{
		Log.d("UI", "OR result" + (InputType.TYPE_TEXT_FLAG_MULTI_LINE | 1));

		View view = inflater.inflate(R.layout.panel_templatefieldedit, null);
		TextView title = (TextView) view.findViewById(R.id.templateTitle);
		EditText text = (EditText) view.findViewById(R.id.templateField);
		text.setInputType(fieldDescriptor.getFieldType());
		title.setText(fieldDescriptor.getFieldName());
		title.setTextSize(getApplicationPreferences().getInt(ApplicationConstants.PREF_TEXT_SIZE,
				ApplicationConstants.PREF_DEF_TEXTSIZE));
		view.setTag(fieldDescriptor.getFieldName());
		if(!isNewTemplate)
		{
			text.setText(fieldDescriptor.getFieldValue());
		}
		if(fieldDescriptor.getFieldType() == InputType.TYPE_CLASS_DATETIME)
		{
			text.setOnFocusChangeListener(dateFieldFocusListener);
			text.setOnClickListener(dateFieldClickListener);
		}
		contentView.addView(view);
	}

	private void closeActivity(int resultCode)
	{
		setResult(resultCode);
		removeTextOnlyFromPath(isNewTemplate ? this.templateName : this.templateName + '['
				+ getResources().getString(R.string.edit) + ']');
		finish();
	}

	private boolean doesFieldNameExist(String fieldName)
	{
		TemplateFieldContainer container;
		for(int i = 0; i < entryFieldList.size(); i++)
		{
			container = entryFieldList.get(i);
			if(container.getFieldName().equals(fieldName))
				return true;
		}
		return false;
	}

	private Dialog getAddFieldDialog()
	{
		final Dialog dialog = getCustomDialog(R.layout.dialog_addfield, R.string.addfield);
		final EditText fieldName = (EditText) dialog.findViewById(R.id.folderDesc);
		Button[] okCancel = getOKCancelButtons(dialog);
		Button btnok = okCancel[0];
		Button btnCancel = okCancel[1];
		final TextView errorText = (TextView) dialog.findViewById(R.id.errorText);
		final Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner);
		ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this, R.array.field_types,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		btnCancel.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				errorText.setVisibility(View.GONE);
				fieldName.setText("");
				dialog.dismiss();
			}
		});
		btnok.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				if(fieldName.getText().toString().equals(""))
				{
					errorText.setText(R.string.template_fieldname_error);
					errorText.setVisibility(View.VISIBLE);
				} else if(doesFieldNameExist(fieldName.getText().toString()))
				{
					errorText.setText(R.string.template_fieldname_exits_error);
					errorText.setVisibility(View.VISIBLE);
				} else
				{
					errorText.setVisibility(View.GONE);
					int fieldType = 0;
					switch(spinner.getSelectedItemPosition())
					{
						case 0:/* text */
							fieldType = 1;
							break;
						case 1:/* number */
							fieldType = 2;
							break;
						case 2:/* date */
							fieldType = 4;
							break;
						case 3:/* email */
							fieldType = 32;
							break;

					}
					TemplateFieldContainer fieldContainer = new TemplateFieldContainer(fieldType, fieldName
							.getText().toString(), null);
					entryFieldList.add(fieldContainer);
					LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
					addTemplateField(fieldContainer, inflater);
					dialog.dismiss();
				}
			}
		});
		return dialog;
	}

	private Dialog getDatePickerDialog()
	{
		final Calendar c = Calendar.getInstance();
		return new DatePickerDialog(this, mDateSetListener, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c
				.get(Calendar.DAY_OF_MONTH));
	}

	@Override
	protected final Dialog onCreateDialog(int id)
	{
		switch(id)
		{
			case DLG_DATE_PICKER:
				return getDatePickerDialog();
			case ApplicationConstants.DIALOG_ADD:
				return getAddFieldDialog();
			default:
				return super.onCreateDialog(id);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		inflateMenu(menu, isNewTemplate ? R.menu.edittemplatemenu : R.menu.edittemplatemenu_update);
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			closeActivity(RESULT_CANCELED);
			return true;
		}
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
			/* Add new folder */
			case R.id.mnu_Save:
				saveTemplate();
				return true;
			case R.id.mnu_AddField:
				showDialog(ApplicationConstants.DIALOG_ADD);
				return true;
		}
		return false;
	}

	private void populateFieldList()
	{
		TemplateFieldContainer container;
		for(int i = 0; i < entryFieldList.size(); i++)
		{
			container = entryFieldList.get(i);
			LinearLayout layout = (LinearLayout) contentView.findViewWithTag(container.getFieldName());
			EditText value = (EditText) layout.findViewById(R.id.templateField);
			container.setFieldValue(value.getText().toString());
		}
	}

	@Override
	protected void populateUI()
	{
		Intent intent = getIntent();
		ImageView templateImage = (ImageView) findViewById(R.id.templateIcon);
		iconId = intent.getStringExtra(ApplicationConstants.EXTRA_TEMPLATE_ICON);
		Bitmap bitmap = ImageUtil.createBitmapFromAsset(getApplicationContext(), iconId);
		templateImage.setImageBitmap(bitmap);
		TextView templateTitle = (TextView) findViewById(R.id.templateName);
		templateName = intent.getStringExtra(ApplicationConstants.EXTRA_TEMPLATE_NAME);
		templateTitle.setText(templateName);
		template = intent.getStringExtra(ApplicationConstants.EXTRA_TEMPLATE);
		folderName = intent.getStringExtra(ApplicationConstants.EXTRA_FOLDER_NAME);
		isNewTemplate = intent.getBooleanExtra(ApplicationConstants.EXTRA_TEMPLATE_ISNEW, true);
		entryFieldList = intent.getParcelableArrayListExtra(ApplicationConstants.EXTRA_FIELD_CONTAINER);

		contentView = (LinearLayout) findViewById(R.id.contentLayout);
		reloadContents();

		addToPath(isNewTemplate ? this.templateName : this.templateName + '['
				+ getResources().getString(R.string.edit) + ']');
		Button btnSave = (Button) findViewById(R.id.dialog_ok);
		if(!isNewTemplate)
		{
			btnSave.setText(R.string.update);
			templateUID = intent.getStringExtra(ApplicationConstants.EXTRA_TEMPLATE_UID);
		}
		btnSave.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				saveTemplate();
			}
		});
	}

	private void reloadContents()
	{
		contentView.removeAllViews();
		Log.d("UI", "Size of entry field List" + entryFieldList.size());
		LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
		for(int i = 0; i < entryFieldList.size(); i++)
		{
			addTemplateField(entryFieldList.get(i), inflater);
		}
	}

	private void saveTemplate()
	{
		populateFieldList();
		SafeEntryTable table = new SafeEntryTable(getApplicationContext());
		if(isNewTemplate)
		{
			table.saveEntry(entryFieldList, folderName, templateName, template, iconId);
			closeActivity(RESULT_OK);
		} else
		{
			table.updateEntry(entryFieldList, folderName, templateUID);
			closeActivity(RESULT_OK);
		}
	}

	@Override
	protected void setupUI(Bundle savedInstance)
	{
		setContentView(R.layout.activity_edittemplate);
	}
}
